package com.basics.api.controller;

import com.basics.api.response.organization.DefaultOrganizationInfoData;
import com.basics.api.vo.UserInfo;
import com.basics.common.constant.SecurityConstants;
import com.basics.common.exception.CustomException;
import com.basics.common.utils.redis.RedisUtil;
import com.basics.framework.config.jwt.BLContext;

import com.basics.organization.entity.CyOrganization;
import com.basics.organization.service.CyOrganizationService;
import com.basics.organization.service.CyOrganizationUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

public class BaseApiController {

    protected static final Logger log = LoggerFactory.getLogger(BaseApiController.class);

    @Autowired
    protected RedisUtil redisUtil;

    @Autowired
    private CyOrganizationUserService cyOrganizationUserService;

    static UserInfo getCurrentUser() {
        UserInfo userInfo = (UserInfo) BLContext.getValue(SecurityConstants.USER_ATTRIBUTES);
        return userInfo==null?new UserInfo():userInfo;
    }

    protected Long getOrganizationId(boolean tx){
        Long userId = getCurrentUser().getUserId();
        DefaultOrganizationInfoData data =  cyOrganizationUserService.getDefaultOrganization(userId);
        if(tx && data==null){
            throw new CustomException("未加入组织");
        }
        return data==null?null:data.getId();
    }

    protected Long getOrganizationId(){
        return getOrganizationId(true);
    }
}
